package com.qing.common.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.view.View

class WaveformView : View {
    private var waveform: FloatArray = FloatArray(0)

    private val paint by lazy {
        Paint().apply {
            color = android.graphics.Color.BLUE
            strokeWidth = 2f
        }
    }

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: android.util.AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: android.util.AttributeSet?, defStyleAttr: Int) : this(
        context, attrs, defStyleAttr, 0
    )

    constructor(
        context: Context, attrs: android.util.AttributeSet?, defStyleAttr: Int, defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes)

    fun setWaveform(data: FloatArray) {
        waveform = data
        postInvalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val width = width.toFloat()
        val height = height.toFloat()
        val dx = width / waveform.size

        for (i in waveform.indices) {
            val x = i * dx
            val amplitude = waveform[i] * height / 2
            canvas.drawLine(x, height / 2 - amplitude, x, height / 2 + amplitude, paint)
        }
    }
}